package com.eshop.modules.activity.rest;

import java.lang.invoke.SerializedLambda;
import com.alibaba.fastjson.JSONObject;
import com.eshop.modules.template.domain.ShippingTemplates;
import java.util.Map;
import java.util.ArrayList;
import com.eshop.enums.SpecTypeEnum;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import org.springframework.beans.BeanUtils;
import com.eshop.modules.product.service.dto.ProductFormatDto;
import com.eshop.modules.product.domain.StoreProductAttrValue;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.eshop.modules.product.domain.StoreProductAttrResult;
import java.util.List;
import java.util.Arrays;
import cn.hutool.core.bean.BeanUtil;
import java.util.LinkedHashMap;
import org.springframework.web.bind.annotation.PostMapping;
import com.eshop.modules.activity.service.dto.StoreSeckillDto;
import org.springframework.web.bind.annotation.DeleteMapping;
import com.eshop.modules.aop.ForbidSubmit;
import java.io.Serializable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.cache.annotation.CacheEvict;
import cn.hutool.core.util.ObjectUtil;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.validation.annotation.Validated;
import com.eshop.modules.activity.domain.StoreSeckill;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import io.swagger.annotations.ApiOperation;
import com.eshop.logging.aop.log.Log;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.data.domain.Pageable;
import com.eshop.modules.activity.service.dto.StoreSeckillQueryCriteria;
import com.eshop.modules.product.service.StoreProductAttrResultService;
import com.eshop.modules.product.service.StoreProductAttrValueService;
import com.eshop.modules.product.service.StoreProductRuleService;
import com.eshop.modules.template.service.ShippingTemplatesService;
import com.eshop.modules.activity.service.StoreSeckillService;
import com.eshop.dozer.service.IGenerator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;

@Api(tags = { "商城:秒杀管理" })
@RestController
@RequestMapping({ "api" })
public class StoreSeckillController
{
    private final IGenerator generator;
    private final StoreSeckillService storeSeckillService;
    private final ShippingTemplatesService shippingTemplatesService;
    private final StoreProductRuleService storeProductRuleService;
    private final StoreProductAttrValueService storeProductAttrValueService;
    private final StoreProductAttrResultService storeProductAttrResultService;
    
    public StoreSeckillController(final IGenerator generator, final StoreSeckillService storeSeckillService, final ShippingTemplatesService shippingTemplatesService, final StoreProductRuleService storeProductRuleService, final StoreProductAttrValueService storeProductAttrValueService, final StoreProductAttrResultService storeProductAttrResultService) {
        this.generator = generator;
        this.storeSeckillService = storeSeckillService;
        this.shippingTemplatesService = shippingTemplatesService;
        this.storeProductRuleService = storeProductRuleService;
        this.storeProductAttrValueService = storeProductAttrValueService;
        this.storeProductAttrResultService = storeProductAttrResultService;
    }
    
    @Log("列表")
    @ApiOperation("列表")
    @GetMapping({ "/yxStoreSeckill" })
    @PreAuthorize("hasAnyRole('admin','YXSTORESECKILL_ALL','YXSTORESECKILL_SELECT')")
    public ResponseEntity getYxStoreSeckills(final StoreSeckillQueryCriteria criteria, final Pageable pageable) {
        return new ResponseEntity(this.storeSeckillService.queryAll(criteria, pageable), HttpStatus.OK);
    }
    
    @CacheEvict(cacheNames = { "yshop:index_data" }, allEntries = true)
    @Log("发布")
    @ApiOperation("发布")
    @PutMapping({ "/yxStoreSeckill" })
    @PreAuthorize("hasAnyRole('admin','YXSTORESECKILL_ALL','YXSTORESECKILL_EDIT')")
    public ResponseEntity update(@Validated @RequestBody final StoreSeckill resources) {
        if (ObjectUtil.isNull(resources.getId())) {
            return new ResponseEntity(this.storeSeckillService.save(resources), HttpStatus.CREATED);
        }
        this.storeSeckillService.saveOrUpdate(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }
    
    @CacheEvict(cacheNames = { "yshop:index_data" }, allEntries = true)
    @ForbidSubmit
    @Log("删除")
    @ApiOperation("删除")
    @DeleteMapping({ "/yxStoreSeckill/{id}" })
    @PreAuthorize("hasAnyRole('admin','YXSTORESECKILL_ALL','YXSTORESECKILL_DELETE')")
    public ResponseEntity delete(@PathVariable final Integer id) {
        this.storeSeckillService.removeById((Serializable)id);
        return new ResponseEntity(HttpStatus.OK);
    }
    
    @CacheEvict(cacheNames = { "yshop:index_data" }, allEntries = true)
    @Log("新增秒杀")
    @ApiOperation("新增秒杀")
    @PostMapping({ "/yxStoreSeckill" })
    @PreAuthorize("hasAnyRole('admin','YXSTORESECKILL_ALL','YXSTORESECKILL_EDIT')")
    public ResponseEntity add(@Validated @RequestBody final StoreSeckillDto resources) {
        return new ResponseEntity(this.storeSeckillService.saveSeckill(resources), HttpStatus.CREATED);
    }
    
    @ApiOperation("获取商品信息")
    @GetMapping({ "/yxStoreSecKill/info/{id}" })
    public ResponseEntity info(@PathVariable final Long id) {
        final Map<String, Object> map = new LinkedHashMap<String, Object>(3);
        final List<ShippingTemplates> shippingTemplatesList = (List<ShippingTemplates>)this.shippingTemplatesService.list();
        map.put("tempList", shippingTemplatesList);
        map.put("ruleList", this.storeProductRuleService.list());
        if (id == 0L) {
            return new ResponseEntity(map, HttpStatus.OK);
        }
        final StoreSeckill storeSeckill = (StoreSeckill)this.storeSeckillService.getById((Serializable)id);
        final StoreSeckillDto productDto = new StoreSeckillDto();
        BeanUtil.copyProperties(storeSeckill, productDto, new String[] { "images" });
        productDto.setSliderImage((List)Arrays.asList(storeSeckill.getImages().split(",")));
        final StoreProductAttrResult storeProductAttrResult = (StoreProductAttrResult)this.storeProductAttrResultService.getOne((Wrappers.<StoreProductAttrResult>lambdaQuery().eq(StoreProductAttrResult::getProductId, storeSeckill.getProductId())).last("limit 1"));
        final JSONObject result = JSON.parseObject(storeProductAttrResult.getResult());
        final List<StoreProductAttrValue> attrValues = (List<StoreProductAttrValue>)this.storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery().eq(StoreProductAttrValue::getProductId, storeSeckill.getProductId()));
        final List<ProductFormatDto> productFormatDtos = attrValues.stream().map(i -> {
            ProductFormatDto productFormatDto = new ProductFormatDto();
            BeanUtils.copyProperties(i, productFormatDto);
            productFormatDto.setPic(i.getImage());
            return productFormatDto;
        }).collect(Collectors.toList());
        if (SpecTypeEnum.TYPE_1.getValue().equals(storeSeckill.getSpecType())) {
            productDto.setAttr(new ProductFormatDto());
            productDto.setAttrs((List)productFormatDtos);
            productDto.setItems((List)result.getObject("attr", (Class)ArrayList.class));
        }
        else {
            this.productFormat(productDto, result);
        }
        map.put("productInfo", productDto);
        return new ResponseEntity(map, HttpStatus.OK);
    }
    
    private void productFormat(final StoreSeckillDto productDto, final JSONObject result) {
        final Map<String, Object> mapAttr = (Map<String, Object>) (result.getObject("value", ArrayList.class)).get(0);
        final ProductFormatDto productFormatDto = ProductFormatDto.builder().pic(mapAttr.get("pic").toString()).price(Double.valueOf(mapAttr.get("price").toString())).cost(Double.valueOf(mapAttr.get("cost").toString())).otPrice(Double.valueOf(mapAttr.get("otPrice").toString())).stock(Integer.valueOf(mapAttr.get("stock").toString())).barCode(mapAttr.get("barCode").toString()).weight(Double.valueOf(mapAttr.get("weight").toString())).volume(Double.valueOf(mapAttr.get("volume").toString())).value1(mapAttr.get("value1").toString()).brokerage(Double.valueOf(mapAttr.get("brokerage").toString())).brokerageTwo(Double.valueOf(mapAttr.get("brokerageTwo").toString())).pinkPrice(Double.valueOf(mapAttr.get("pinkPrice").toString())).pinkStock(Integer.valueOf(mapAttr.get("pinkStock").toString())).seckillPrice(Double.valueOf(mapAttr.get("seckillPrice").toString())).seckillStock(Integer.valueOf(mapAttr.get("seckillStock").toString())).build();
        productDto.setAttr(productFormatDto);
    }
}
